package cn.itcast.n8;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static cn.itcast.n2.util.Sleeper.sleep;

/**
 * @author: AirMan
 * @date: 2025/4/23 20:37
 * @description:
 */

@Slf4j(topic = "c.TestReentrantReadWritreLock")
public class TestReentrantReadWritreLock {

    public static void main(String[] args) {
        DataContainer dataContainer = new DataContainer();

        new Thread(() -> {
            try {
                dataContainer.wrire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t3").start();

        Sleeper.sleep(1);
        new Thread(() -> {
            int[] read = null;
            try {
                read = dataContainer.read();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug(Arrays.toString(read));
        }, "t1").start();

        new Thread(() -> {
            int[] read = null;
            try {
                read = dataContainer.read();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug(Arrays.toString(read));
        }, "t2").start();



    }
    @Slf4j(topic = "c.DataContainer")
    static class DataContainer {

        private int[] data = new int[]{1, 1, 1};
        private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
        private ReentrantReadWriteLock.ReadLock r = rw.readLock();
        private ReentrantReadWriteLock.WriteLock w = rw.writeLock();

        private int[] read() throws InterruptedException {
            log.debug("获取读取锁...");
            r.lock();
            try {
                log.debug("读取数据中！");
//                TimeUnit.SECONDS.sleep(1);
                return data;
            } finally {
                r.unlock();
            }
        }

        public int[] wrire() throws InterruptedException {
            log.debug("获取写入锁...");
            w.lock();
            try {
                log.debug("正在写入数据！");
                TimeUnit.SECONDS.sleep(2);
                data[0] = data[1] = data[2] = 2;
                return data;
            } finally {
                w.unlock();
            }
        }

    }
}
